package com.wzp.fulfill.application.command.executor;

import com.wzp.fulfill.application.command.AuditInterceptedFulfillOrderCommand;
import com.wzp.fulfill.application.command.dto.InterceptedFulfillOrderAuditResultDTO;
import com.wzp.fulfill.domain.event.OrderFulfillDeniedEvent;
import com.wzp.fulfill.domain.model.fulfillorder.FulfillOrder;
import com.wzp.fulfill.domain.gateway.DomainEventGateway;
import com.wzp.fulfill.domain.gateway.FulfillOrderGateway;
import com.wzp.fulfill.domain.gateway.WarehouseApiGateway;
import com.wzp.fulfill.domain.service.LogisticsDomainService;
import com.wzp.fulfill.domain.model.warehouse.Warehouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AuditInterceptedFulfillOrderCommandExecutor {

    @Autowired
    private LogisticsDomainService logisticsDomainService;
    @Autowired
    private FulfillOrderGateway fulfillOrderGateway;
    @Autowired
    private WarehouseApiGateway warehouseApiGateway;
    @Autowired
    private DomainEventGateway domainEventGateway;

    public void execute(AuditInterceptedFulfillOrderCommand auditInterceptedFulfillOrderCommand) {
        // 先提取审核数据
        InterceptedFulfillOrderAuditResultDTO interceptedFulfillOrderAuditResultDTO = auditInterceptedFulfillOrderCommand.getInterceptedFulfillOrderAuditResultDTO();
        Long orderId = interceptedFulfillOrderAuditResultDTO.getOrderId();
        Boolean auditResult = interceptedFulfillOrderAuditResultDTO.getAuditResult();

        // 如果审核通过了，则分物流和下库房
        if (auditResult) {
            FulfillOrder fulfillOrder = fulfillOrderGateway.getByOrderId(orderId);
            Warehouse warehouse = fulfillOrderGateway.getAllocatedWarehouse(orderId);
            logisticsDomainService.allocateLogistics(fulfillOrder, warehouse);

            warehouseApiGateway.sendFulfillOrder(fulfillOrder, warehouse);
        }
        // 如果审核没通过，则发布订单履约被拒绝的领域事件
        else {
            OrderFulfillDeniedEvent orderFulfillDeniedEvent = new OrderFulfillDeniedEvent();
            domainEventGateway.publishOrderFulfillDeniedEvent(orderFulfillDeniedEvent);
        }
    }

}
